LD		:= $(CROSS_COMPILE)ld
CC		:= $(CROSS_COMPILE)gcc
CPP		:= $(CROSS_COMPILE)cpp
AR		:= $(CROSS_COMPILE)ar
STRIP	:= $(CROSS_COMPILE)strip
MACH:=$(shell getconf LONG_BIT)

exclude_modules?=ipc

DBG_MODE:=0

TOP  := $(shell pwd)
my_dir :=$(TOP)

CFLAGS := -I$(my_dir)/mshell -I$(my_dir)/mshell/include -DUSE_HOSTCC -O2 -Wall -Wno-unused-function \
-Wno-unused-label -Wno-unused-variable 
LDFLAGS:=
ifeq ($(DBG_MODE),1)
CFLAGS += -g
endif
#
#unfortunately jpeglib does not support pkg-config
#
build_dir:=$(TOP)/build
ifeq ($(CROSS_COMPILE),)
bin_dir := $(TOP)/bin/x86
else
bin_dir := $(TOP)/bin/$(CROSS_COMPILE)
endif
source_dir:=$(TOP)/mshell
sources  := $(wildcard $(source_dir)/*.c)

ifeq ($(CROSS_COMPILE),)
ifeq ($(findstring "ipc",$exclude_modules),"")
LDFLAGS+=-ljpeg -lpthread
else
sources :=$(filter-out $(source_dir)/cmd_ipc.c,$(sources))
endif
ifeq ($(MACH),64)
CFLAGS+=-m32
endif
else
sources :=$(filter-out $(source_dir)/cmd_ipc.c,$(sources))
endif


static_dir:=$(build_dir)/static
static_objs:=$(sources:$(source_dir)/%.c=$(static_dir)/%.o)
shared_dir:=$(build_dir)/shared
shared_objs:=$(sources:$(source_dir)/%.c=$(shared_dir)/%.o)

.PHONY: all static_libary shared_libary mcushell 

all: sanity_checking static_libary mcushell install
#shared_libary
shared_libary:CFLAGS += -Wl,-z,defs,-export-dynamic -fPIC
shared_libary:LDFLAGS+= -shared 
ifneq ($(DBG_MODE),1)
shared_libary:$(shared_objs)
	$(LD) $(LDFLAGS) -o $(bin_dir)/libdevtool.so $(shared_objs)
	$(STRIP) --strip-all $(bin_dir)/libdevtool.so -o $(bin_dir)/libdevtool.so
else
shared_libary:$(shared_objs)
	$(LD) $(LDFLAGS) -o $(bin_dir)/libdevtool.so $(shared_objs)
endif

static_libary:$(static_objs)
	$(AR) rcsv $(bin_dir)/libdevtool.a $(static_objs)


ifneq ($(DBG_MODE),1)
mcushell:$(static_objs) $(bin_dir)/main.o
	$(CC) $(CFLAGS)  -o $(bin_dir)/$@ $^ $(LDFLAGS)
	$(STRIP) --strip-all $(bin_dir)/$@
else
mcushell:$(static_objs) $(bin_dir)/main.o
	$(CC) $(CFLAGS) -o $(bin_dir)/$@ $^  $(LDFLAGS)
endif

install:

$(static_dir)/%.o: $(source_dir)/%.c | $(static_dir)
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -o $@ -c $<
	
$(shared_dir)/%.o: $(source_dir)/%.c | $(shared_dir)
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -o $@ -c $<

$(bin_dir)/main.o:$(my_dir)/main.c
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -o $@ -c $<

$(static_dir) $(shared_dir) :
	@mkdir -p $@
sanity_checking:
	@mkdir -p $(bin_dir)
	@echo "MACH is ${MACH} system"
.PHONY: clean distclean
clean:
	rm -rf $(build_dir) 
distclean:clean
	rm -rf $(TOP)/bin

